<?php
/*
 *      core.php
 *      
 *      Copyright 2011 unro <unro.ua@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
 
include ("config.php");

// Открываем подключение
function OpenConn()
	{
		global $db_host, $db_port, $db_username, $db_userpass, $db_auth, $db_encode;
		mysql_connect("$db_host:$db_port", "$db_username", "$db_userpass") or die (mysql_error());
		mysql_select_db("$db_auth")or die("Could not select database");
		mysql_query("SET CHARACTER SET $db_encode");
		mysql_query("SET NAMES $db_encode");
	}
	
// Функция времени
function GetDataTime($timestamp = 0) 
	{
	if ($timestamp)
		return date("Y-m-d H:i:s", $timestamp);
	else
		return date("Y-m-d H:i:s");
	}
function gmtime() 
	{
	return strtotime(GetDataTime());
	}



// Удаление топа
function DelTop($name)
	{
		global $SERVERADDR;
		OpenConn();
		mysql_query("DELETE FROM `game_top` WHERE `name`='$name'");
		MakeLog($_SESSION["userID"],9,$name);
		header("Location: $SERVERADDR/admin.php");
	}

// Добавление топа
function AddTop($name,$link,$cost)
	{
		global $SERVERADDR;
		OpenConn();
		$check = mysql_query("SELECT * FROM `game_top` WHERE `name`='$name'");
		$c = mysql_num_rows($check);
		if($name!="")
		{
		if($c>0)
			{ DelTop($name); AddTop($name,$link,$cost); }
		else
			{
				mysql_query("INSERT INTO `game_top` (`name`,`link`,`cost`) VALUES ('$name','$link','$cost')");
				MakeLog($_SESSION["userID"],8,$name);
			}
		}
		header("Location: $SERVERADDR/admin.php");
	}

		
// Логирование
function MakeLog($id=0, $message, $more="")
	{
		include ("message.php");
		$time = GetDataTime();
		$ip = $_SERVER['REMOTE_ADDR'];
		$mess = $logmessage["$message"];
		mysql_query("INSERT INTO `vote_log` (`uid`,`ip`,`message`,`eventtime`) VALUES ('$id','$ip','$mess','$time')");
	}


// Получаем ИД юзера	
function GetUserId($login)
	{
		$select = mysql_query("SELECT `id` FROM `account` WHERE username='$login'");
		$array = mysql_fetch_array($select);
		return $array['id'];
	}

// Получаем аккаунт
function GetUserInfo($id)
	{
		$select = mysql_query("SELECT `username`, `bonuses` FROM `account` WHERE `id`='$id'");
		$array = mysql_fetch_array($select);
		return $array;		
	}
	
// Получаем пасс юзера
function GetUserPass($login)
	{
		$select = mysql_query("SELECT `sha_pass_hash` FROM `account` WHERE username='$login'");
		$array = mysql_fetch_array($select);
		return $array['sha_pass_hash'];
	}
	
// Проверяем логин и пароль
function CheckValidation($pass, $login)
	{
		$sph =  sha1(strtoupper("$login") .":". strtoupper("$pass"));
		if($sph == GetUserPass($login))
			{ return true; }
		else { return false; }
	}

// Проверяем существование юзера
function CheckUserExist($login)
	{
		$s = mysql_query("SELECT * FROM `account` WHERE username='$login'");
		$count = mysql_num_rows($s);
			if ($count==1) { return true; }
			else { return false; }
	}
	
function CheckPossVote($uid)
	{
		$s = mysql_query("SELECT `block_vote` FROM `account` WHERE `id`='$uid'");
		$a = mysql_fetch_array($s);
		if($a["block_vote"]!=1)
			{ return true; } else { return false; }
	}
	
// Начисляем бонусы
function DistributeBonuses($uid, $count)
	{
		mysql_query("UPDATE `account` SET `bonuses`=bonuses+$count WHERE `id`='$uid'");		
	}
	
// проверяем возможность голосовать
function CheckUserVote($sid, $uid)
	{
		$select = mysql_query("SELECT * FROM `vote_var` WHERE `topid`='$sid' AND `userid`='$uid'");
		$array = mysql_fetch_array($select);
		$count = mysql_num_rows($select);
		if ($count == 0)
			{ return "<input type='button' onclick=location.href='./mod/vote.php?sid=$sid' value='Проголосовать!'>"; }
		else
			{
				$last_votetime = $array["votetime"];
				$time = GetDataTime(gmtime() - 86400);
				if($last_votetime < $time)
					{ return "<input type='button' onclick=location.href='./mod/vote.php?sid=$sid' value='Проголосовать!'>"; }
				else 
					{ return "<i><font color='red'>Уже голосовали!</font></i>"; }
			}
	}

// Получаем ГМ уровень
function GetGMLevel($uid)
	{
		$select = mysql_query("SELECT `gmlevel` FROM `account_access` WHERE `id`='$uid'");
		$count = mysql_num_rows($select);
		$array = mysql_fetch_array($select);
		if($count!=0)
		return $array['gmlevel'];
	}
	
// ошибки
function PrintError($errno)
	{
		include ("./mod/message.php");
		$error = $errmessage["$errno"];	
		return $error;
	}

// Сброс сессии
function DROP($errno)
	{
		global $SERVERADDR;
		sleep(2);
		header("Location: $SERVERADDR/login.php?errno=$errno");
		exit;
	}
	
// Выход
function LOGOUT()
	{
		global $SERVERADDR;
		$_SESSION["login_mode"]=0;
		$_SESSION["admin"]=0;
		header("Location: $SERVERADDR/login.php");
		exit;
	}


// Проверка существования сессии
function SESSION()
{
	session_start();

	if ($_SESSION["login_mode"]!=1)
		{
			global $SERVERADDR;
			sleep(2);
			header("Location: $SERVERADDR/login.php");
			exit;
		}
}

// Проверка существования сессии администратора
function ADMINSESSION()
{
	SESSION();
	if ($_SESSION["admin"]!=1)
		{
			DROP(3);
		}
}

?>
